"use client"; // 确保这是一个客户端组件

import React, { useState } from 'react';
import { useRouter } from 'next/navigation'; 
import Cookies from 'js-cookie'; // 使用 js-cookie 处理客户端 Cookie
import { addBlog } from '@/util/actions/blogAction';

const AddBlogPage = () => {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    setLoading(true);

    const token = Cookies.get('token'); // 使用 js-cookie 获取 token

    if (!token) {
      setError("未找到 token");
      setLoading(false);
      return;
    }

    try {
      const blogId = await addBlog(token, { title, content });
      console.log("成功添加博客, ID:", blogId);
      // 重定向到博客详情页或其他页面
    //   router.push(`/blog/${blogId}`);
    router.push(`/blog`);
    } catch (error) {
      setError(error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <h2>添加博客</h2>
      <form onSubmit={handleSubmit}>
        <div>
          <label>标题</label>
          <input
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
          />
        </div>
        <div>
          <label>内容</label>
          <textarea
            value={content}
            onChange={(e) => setContent(e.target.value)}
            required
          />
        </div>
        {error && <p style={{ color: 'red' }}>{error}</p>}
        <button type="submit" disabled={loading}>
          {loading ? '提交中...' : '提交'}
        </button>
      </form>
    </div>
  );
};

export default AddBlogPage;
